package com.tgy.crud.service.impl;

import com.tgy.crud.domain.Person;
import com.tgy.crud.domain.User;
import com.tgy.crud.service.CrudService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service
public class CrudServiceImpl implements CrudService {

    private static ArrayList<Person> userList;

    static {


        userList = new ArrayList<>();

        userList.add(new Person(1,"张三",21,1,new Date(),"更值得boy"));
        userList.add(new Person(2,"李四",20,2,new Date(),"666"));
        userList.add(new Person(3,"王五",24,2,new Date(),"大爷"));
        userList.add(new Person(4,"赵六",25,1,new Date(),"厉害了我的"));
        userList.add(new Person(5,"田七",23,1,new Date(),"哈哈哈"));
        userList.add(new Person(6,"胡巴",25,2,new Date(),"你是睡"));
        userList.add(new Person(7,"译意",22,1,new Date(),"阿萨德的"));
        userList.add(new Person(8,"方增",24,2,new Date(),"是潇洒的说的"));
        userList.add(new Person(9,"范型",23,2,new Date(),"阿斯顿"));
        userList.add(new Person(10,"烫金",21,1,new Date(),"先擦上的"));

    }


    @Override
    public List<Person> findAllPersons() {

        return userList;
    }

    @Override
    public Person findPersonById(Integer id) {


        for (Person person : userList) {

            if (person.getId().equals(id)){

                return  person;
            }
        }

        return null;
    }

    @Override
    public boolean insertPerson(Person person) {

        if (person == null){

            return false;
        }

        Integer personId = -1;
        for (Person per : userList) {

            if (per.getId() > personId){

                personId = per.getId();
            }
        }

        person.setId(personId + 1);
        userList.add(person);

        return true;
    }

    @Override
    public boolean updatePerson(Person person) {

        if (person == null){

            return false;
        }

        Person tmpPerson = null;
        for (Person person1 : userList) {

            if (person1.getId().equals(person.getId())){

                tmpPerson = person1;
            }
        }

        if (tmpPerson == null){

            return false;
        }

        BeanUtils.copyProperties(person,tmpPerson,"id");

        return true;
    }

    @Override
    public boolean deletePerson(Integer id) {


        for (Iterator<Person> iterator = userList.iterator();iterator.hasNext();){

            Person next = iterator.next();

            if (next.getId().equals(id)){

                iterator.remove();
                return  true;
            }
        }

        return false;
    }
}
